package com.ezops.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ezops.dao.facade.IClientDataTransferFacade;
import com.ezops.dto.DownloadableReport;
import com.ezops.exception.EzopsUIException;
import com.ezops.models.ClientEzopsFieldMappingModel;
import com.ezops.util.Report;
import com.ezops.util.Report.Row;

@Controller
@RequestMapping("/fileuploaddownload")
public class FileUploadDownloadController {

	@Autowired
	private IClientDataTransferFacade facade;

	protected static Logger logger = LoggerFactory
			.getLogger(FileUploadDownloadController.class);

	// private static final String TRADE_EXPORT_PATH =
	// "C:\\Users\\Administrator\\EZOPS\\Input";
	private static final String TRADE_EXPORT_PATH = System
			.getProperty("user.home") + "\\EZOPS\\Input\\";

	//private static final String SECURE_PATH = System.getProperty("user.home")
		//	+ "\\USB\\Reports10302014\\";
	
	DateFormat format = new SimpleDateFormat("MMddyyyy");

	/**
	 * Import file in Trade monitor
	 * 
	 * @param file
	 * @return
	 * @throws EzopsUIException
	 */
	@RequestMapping(value = "/csvupload", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	Map<String, String> handleFileUpload(
			@RequestParam("file") MultipartFile file) throws EzopsUIException {

		Map<String, String> responseMesage = new HashMap<String, String>();

		if (!file.isEmpty()) {
			try {
				String fileName = file.getOriginalFilename();
				byte[] byteArr = file.getBytes();
				BufferedOutputStream stream = new BufferedOutputStream(
						new FileOutputStream(new File(TRADE_EXPORT_PATH
								+ fileName)));
				stream.write(byteArr);
				stream.close();

				responseMesage.put("message",
						"Sucessfully uploaded the mapping.");
				return responseMesage;

			} catch (Exception e) {
				// responseMesage.put("message",
				// "Unable to upload the mapings.");
				logger.error("Unable to upload the mapings" + e.getMessage());
				throw new EzopsUIException(
						"Error Ocuured while uploading mappings");
			}
		}
		return responseMesage;

	}

	/**
	 * Import validation Rules
	 * 
	 * @param file
	 * @return
	 * @throws EzopsUIException
	 */
	@RequestMapping(value = "/importValidationRule", method = RequestMethod.POST)
	public String handleValidationRule(@RequestParam("file") MultipartFile file)
			throws EzopsUIException {

		if (!file.isEmpty()) {
			try {
				String fileName = file.getOriginalFilename();
				byte[] byteArr = file.getBytes();
				BufferedOutputStream stream = new BufferedOutputStream(
						new FileOutputStream(new File(TRADE_EXPORT_PATH
								+ fileName)));
				stream.write(byteArr);
				stream.close();
			} catch (Exception e) {
				logger.error("Unable to import rules" + e.getMessage());
				throw new EzopsUIException(
						"Error Ocuured while importing rules");
			}
		}
		return "redirect:/rule/getValidationRules";
	}

	/**
	 * import field mappings
	 * 
	 * @param file
	 * @return
	 */
	@RequestMapping(value = "/importfieldmappings", method = RequestMethod.POST)
	public String importFieldMappings(@RequestParam("file") MultipartFile file) {

		if (!file.isEmpty()) {
			try {
				List<ClientEzopsFieldMappingModel> mappingModels = facade
						.convertTo(file.getInputStream());
				facade.saveFieldMappings(mappingModels);

			} catch (Exception e) {
				logger.error("Something wrong while importing mappings."
						+ e.getMessage());
				return "Error Occurred";
			}
		}
		return "redirect:/fieldMapping";
	}

	/**
	 * Export field mappings in CSV and Excel format
	 * 
	 * @return
	 * @throws EzopsUIException
	 */
	@RequestMapping(value = "/exportcsvandexcel", method = RequestMethod.GET)
	public ModelAndView exportCsvAndExcel(
			@RequestParam("exportFileFormat") String exportFileFormat)
			throws EzopsUIException {

		/*
		 * if(exportFileFormat.equals("CSV")){ } else
		 * if(exportFileFormat.equals("CSV")){ }
		 */
		Report report = null;
		try {
			report = new Report(new File(System.getProperty("user.home")
					+ "/EZOPS/FieldMappingTemplate.xlsx"));

			List<ClientEzopsFieldMappingModel> models = facade.getAllMapping(
					"1", "1");
			for (ClientEzopsFieldMappingModel model : models) {
				Row row = report.createRow();
				row.setValue(0, model.getClientField().getFieldName());
				row.setValue(1, model.getEzopsField().getEzopsFieldName());
			}
			// return new ModelAndView("excelView", "report", report);
			return new ModelAndView("excelView", "report",
					new DownloadableReport("FieldMappings.xls", report));

		} catch (Exception e) {
			logger.error("There is some issue in fieldmappins export"
					+ e.getMessage());
			throw new EzopsUIException(
					"Error Ocuured while exporting fieldmappings");
		}
	}

	/**
	 * Export Validation Rule in CSV and Excel format
	 * 
	 * @return
	 * @throws EzopsUIException
	 */
	@RequestMapping(value = "/exportruleincsvandexcel", method = RequestMethod.GET)
	public ModelAndView exportRulesInCsvAndExcel(
			@RequestParam("exportFileFormat") String exportFileFormat)
			throws EzopsUIException {

		/*
		 * if(exportFileFormat.equals("CSV")){ } else
		 * if(exportFileFormat.equals("CSV")){ }
		 */
		Report report = null;
		try {
			report = new Report(new File(System.getProperty("user.home")
					+ "/EZOPS/ezopsValidation.xlsx"));

			return new ModelAndView("excelView", "report",
					new DownloadableReport("ValidationRules.xls", report));

		} catch (Exception e) {
			logger.error("Unable to download " + e.getMessage());
			throw new EzopsUIException("Error occured while export rule");
		}
	}

	/**
	 * Import validation Rules
	 * 
	 * @param file
	 * @return
	 * @throws EzopsUIException
	 */
	@RequestMapping(value = "/uploadsecurefile", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	Map<String, String> uploadToSecureLocation(
			@RequestParam("file") MultipartFile file) throws EzopsUIException {

		Map<String, String> responseMesage = new HashMap<String, String>();

		if (!file.isEmpty()) {
			try {
				String fileName = file.getOriginalFilename();
				byte[] byteArr = file.getBytes();
				String currentDate = format.format(new Date());
				String fs = System.getProperty("file.separator");
				String SECURE_PATH = System.getProperty("user.home")+ fs + "USB" + fs + "Reports"+currentDate;
				File folderPath = new File(SECURE_PATH);
				if(!folderPath.exists()){
					folderPath.mkdir();
				}
				BufferedOutputStream stream = new BufferedOutputStream(
						new FileOutputStream(folderPath+fs+fileName));
				stream.write(byteArr);
				stream.close();
				responseMesage.put("message",
						"Sucessfully sent the file to secure location.");

			} catch (Exception e) {
				logger.error("Unable to send file to secure location"
						+ e.getMessage());
				throw new EzopsUIException(
						"Error Ocuured while putting file to secure location");
			}
		}
		return responseMesage;
	}

}
